package com.example.administrator.myapplication.data.source.local;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.administrator.myapplication.data.Task;
import com.example.administrator.myapplication.data.source.TaskDataSource;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by Administrator on 2017/11/27.
 */

public class TaskLocalDataSource implements TaskDataSource{

// 排序问题



    private static TaskLocalDataSource instance;

    private TaskDbHelper taskDbHelper;

    public TaskLocalDataSource(Context context) {
        taskDbHelper = new TaskDbHelper(context);
    }

    public static TaskLocalDataSource getInstance(Context context){
        if (instance == null)
            instance = new TaskLocalDataSource(context);
        return instance;
    }



    @Override
    public void getTasks(LoadTasksCallback callback) {
        List<Task> tasks = new ArrayList<>();
        SQLiteDatabase db = taskDbHelper.getReadableDatabase();
        String[] projection = new String[]{
          "id","name","position","pipeOut","brand","consumption","date","imgPath"
        };
        Cursor cursor = db.query("PIPE",projection,null,null,
                null,null,"date desc");
        if (cursor != null && cursor.getCount() > 0){
            while (cursor.moveToNext()) {
                String id = cursor.getString(cursor.getColumnIndexOrThrow("id"));
                String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
                String position = cursor.getString(cursor.getColumnIndexOrThrow("position"));
                int pipeOut = cursor.getInt(cursor.getColumnIndexOrThrow("pipeOut"));
                String brand = cursor.getString(cursor.getColumnIndexOrThrow("brand"));
                float consumption = cursor.getFloat(cursor.getColumnIndexOrThrow("consumption"));
                long date = cursor.getLong(cursor.getColumnIndexOrThrow("date"));
                String imgPath = cursor.getString(cursor.getColumnIndexOrThrow("imgPath"));
                List<String> imgList;
                String[] split = imgPath.split(";");
                imgList = Arrays.asList(split);
                Task task = new Task(id, name, position, pipeOut, brand, consumption, date, imgList);
                tasks.add(task);
            }
        }

        if (cursor != null)
            cursor.close();
        db.close();

        if (tasks.isEmpty())
            callback.onDataNotAvaliable();
        else
            callback.onTasksLoaded(tasks);
    }

    @Override
    public void getSearchedTasks(String selectionContent, LoadSerachedTasksCallback callback) {
        List<Task> tasks = new ArrayList<>();
        SQLiteDatabase db = taskDbHelper.getReadableDatabase();
        String[] projection = new String[]{
                "id","name","position","pipeOut","brand","consumption","date","imgPath"
        };
        String nameSelection = "position LIKE ? OR name LIKE ?";
        String[] selectionArgs = new String[]{"%"+selectionContent+"%","%"+selectionContent+"%"};

        Cursor cursorOrderByName = db.query("PIPE", projection, nameSelection,
                selectionArgs, null, null, "date desc");
//        String sql = "selece * from PIPE where name like '%" +
//                selectionContent+"%'" +
//                "or"+
//                "position like '%"+
//                selectionContent+"%' order by date desc";

        if (cursorOrderByName != null && cursorOrderByName.getCount() >0) {
            while (cursorOrderByName.moveToNext()) {
                String id = cursorOrderByName.getString(cursorOrderByName.getColumnIndexOrThrow("id"));
                String name = cursorOrderByName.getString(cursorOrderByName.getColumnIndexOrThrow("name"));
                String position = cursorOrderByName.getString(cursorOrderByName.getColumnIndexOrThrow("position"));
                int pipeOut = cursorOrderByName.getInt(cursorOrderByName.getColumnIndexOrThrow("pipeOut"));
                String brand = cursorOrderByName.getString(cursorOrderByName.getColumnIndexOrThrow("brand"));
                float consumption = cursorOrderByName.getFloat(cursorOrderByName.getColumnIndexOrThrow("consumption"));
                long date = cursorOrderByName.getLong(cursorOrderByName.getColumnIndexOrThrow("date"));
                String imgPath = cursorOrderByName.getString(cursorOrderByName.getColumnIndexOrThrow("imgPath"));

                String[] split = imgPath.split(";");
                List<String> imgPathList = Arrays.asList(split);

                Task task = new Task(id,name,position,pipeOut,brand,consumption,date,imgPathList);

                tasks.add(task);
            }
        }

        if (cursorOrderByName != null)
            cursorOrderByName.close();

//        Cursor cursorOrderByPosition = db.query("PIPE", projection, positionSelection,
//                selectionArgs, null, null, "date desc");
//        if (cursorOrderByPosition != null && cursorOrderByPosition.getCount() > 0) {
//            while (cursorOrderByPosition.moveToNext()) {
//                String id = cursorOrderByName.getString(cursorOrderByName.getColumnIndexOrThrow("id"));
//                String name = cursorOrderByName.getString(cursorOrderByName.getColumnIndexOrThrow("name"));
//                String position = cursorOrderByName.getString(cursorOrderByName.getColumnIndexOrThrow("position"));
//                int pipeOut = cursorOrderByName.getInt(cursorOrderByName.getColumnIndexOrThrow("pipeOut"));
//                String brand = cursorOrderByName.getString(cursorOrderByName.getColumnIndexOrThrow("brand"));
//                float consumption = cursorOrderByName.getFloat(cursorOrderByName.getColumnIndexOrThrow("consumption"));
//                String date = cursorOrderByName.getString(cursorOrderByName.getColumnIndexOrThrow("date"));
//                String imgPath = cursorOrderByName.getString(cursorOrderByName.getColumnIndexOrThrow("imgPath"));
//
//                String[] split = imgPath.split(";");
//                List<String> imgPathList = Arrays.asList(split);
//
//                Task task = new Task(id,name,position,pipeOut,brand,consumption,date,imgPathList);
//
//                if (!tasks.contains(task)){
//                    tasks.add(task);
//                }
//            }
//        }
//
//        if (cursorOrderByPosition != null)
//            cursorOrderByPosition.close();

        db.close();

        if (tasks.isEmpty())
            callback.onDataNotAvaliable();
        else
            callback.onTasksLoaded(tasks);

    }

    @Override
    public void getTask(String id,GetTaskCallback callback) {
        Task task = null;
        SQLiteDatabase db = taskDbHelper.getReadableDatabase();
        String[] projection = new String[]{
                "name","position","pipeOut","brand","consumption","date","imgPath"
        };
        String selection = "id LIKE ?";
        String[] selectionArgs = new String[]{id};
        Cursor cursor = db.query("PIPE", projection, selection, selectionArgs,
                null, null, null);
        if (cursor != null && cursor.getCount() > 0 ){
            cursor.moveToFirst();
            String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
            String position = cursor.getString(cursor.getColumnIndexOrThrow("position"));
            int pipeOut = cursor.getInt(cursor.getColumnIndexOrThrow("pipeOut"));
            String brand = cursor.getString(cursor.getColumnIndexOrThrow("brand"));
            float consumption = cursor.getFloat(cursor.getColumnIndexOrThrow("consumption"));
            long date = cursor.getLong(cursor.getColumnIndexOrThrow("date"));
            String imgPath = cursor.getString(cursor.getColumnIndexOrThrow("imgPath"));
            List<String> imgList = null;
            String[] split = imgPath.split(";");
            imgList = Arrays.asList(split);
            task = new Task(id, name, position, pipeOut, brand, consumption, date, imgList);
        }

        if (cursor != null)
            cursor.close();
        db.close();

        if (task != null)
            callback.onTaskLoaded(task);
        else
            callback.onDataNotAvaliable();
    }

    @Override
    public void saveTask(Task task) {
        SQLiteDatabase db = taskDbHelper.getReadableDatabase();


        ContentValues values = new ContentValues();
        values.put("id",task.getId());
        values.put("name",task.getName());
        values.put("position",task.getPosition());
        values.put("pipeOut",task.getPipeOut());
        values.put("brand",task.getBrand());
        values.put("consumption",task.getConsumption());
        values.put("date",task.getDate());


        StringBuilder builder = new StringBuilder();
        List<String> imgPathList = task.getImgPath();
        if (imgPathList != null && imgPathList.size() > 0){
            for (String s : imgPathList) {
                builder.append(s);
                builder.append(";");
            }
            builder.deleteCharAt(builder.length()-1);//删掉最后一个分号
        }
        String imgPath = builder.toString();

        values.put("imgPath",imgPath);
        db.insertOrThrow("PIPE",null,values);
        db.close();
    }

    @Override
    public void updateTask(Task task) {
        SQLiteDatabase db = taskDbHelper.getReadableDatabase();

        ContentValues values = new ContentValues();
        values.put("name",task.getName());
        values.put("position",task.getPosition());
        values.put("pipeOut",task.getPipeOut());
        values.put("brand",task.getBrand());
        values.put("consumption",task.getConsumption());
        values.put("date",task.getDate());
        StringBuilder builder = new StringBuilder();
        List<String> imgPathList = task.getImgPath();
        if (imgPathList != null && imgPathList.size() > 0){
            for (String s : imgPathList) {
                builder.append(s);
                builder.append(";");
            }
            builder.deleteCharAt(builder.length()-1);//删掉最后一个分号
        }
        String imgPath = builder.toString();
        values.put("imgPath",imgPath);

        String whereClause = "id = ?";
        String[] whereArgs = new String[]{task.getId()};
        db.update("PIPE",values,whereClause,whereArgs);
        db.close();
    }
}
